<?php
/**
 * 环信群操作
 */

namespace App\Services\Easemob;

use Easemob\Auth;
use Easemob\Group;
use Easemob\Message;
use Easemob\User;
use Easemob\UserMetadata;

use App\Models\Member\Member;

use App\Services\Com\UtilService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

use App\Services\Easemob\UserAuth as EasemobUserAuth;
use Easemob\Http\Http;


class Messages extends Base
{
    
    /** 
     * 推送
     * $param['member_uuid']
     * $param['title']
     * $param['content']
     * $param['ext']['router']
     * 
         * 推送策略。说明：
        - 0：厂商通道优先，失败时走环信通道。
        - 1：在线或者离线都通过环信通道推送。
        -（默认）2：只通过第三方厂商推送（失败后直接丢弃）。
        - 3：环信通道优先，在线走环信，离线走厂商。
     * 
     * @throws \Exception
     */
    public static function pushMsg(array $param = [])
    {
        $auth = EasemobUserAuth::auth();
        $easemobToken = $auth->getEasemobToken();
        $apiUr = $auth->getBaseUri();
        $headers = $auth->headers();
        $uri = $apiUr.'/push/single';
        $body = [
                    'targets'=>[UtilService::memberUuidToImAccount($param['member_uuid'])],
                    'strategy'=>2, //1：在线或者离线都通过环信通道推送。
                    'pushMessage'=>[
                        'title'=>$param['title'] ?? '',
                        'content'=>$param['content'] ?? '',
                        'ext'=>['router'=>$param['ext']['router']],
                    ]
                ];

        $resp = Http::post($uri, $body, $headers);
        if (!$resp->ok()) {
            Log::alert(var_export($resp,true));
        }else{
            // Log::info(var_export($resp,true));
            if( env('LOG_DEBUG') != false ){
                Log::info(var_export($resp,true));
            }
        }
        return $resp;
    }

    /** 获取聊天消息
     * @param $param
     * @throws \Exception
     */
    public static function getHistoryAsLocalFile(array $param)
    {
        $auth = self::getInstance();
        $message = new Message($auth);
        return $message->getHistoryAsLocalFile($param['date'], $param['filename']);
    }

    /** 
     * 设置用户的离线推送设置
     * $fileurl = Messages::offlinePush('0d7a8493-2cad-4485-b143-70df57078e1e');die;
     
        旧版本 https://docs-im.easemob.com/ccim/rest/pushconfig?s[]=免打扰#设置免打扰模式
        关
        curl -X PUT -H "Authorization: Bearer YWMtpy1QknFCEe2TujGacnLHDjagngqIQTVUsexhz-g5I-6VJ6Ny6VFEraDajvpQ9CsxAgMAAAGEzGe5CQAnjQAeMfbznhjzQxt4h30ZLgyw5AWAUZYcWZFR9b8msilwjQ" -i  "https://a1-v2.easemob.com/1148220627103272/migo/users/842be6aaef302dbffb2edabca32ba11f" -d '{"notification_no_disturbing": true,"notification_no_disturbing_start": "0","notification_no_disturbing_end": "24"}'
        开
        curl -X PUT -H "Authorization: Bearer YWMtpy1QknFCEe2TujGacnLHDjagngqIQTVUsexhz-g5I-6VJ6Ny6VFEraDajvpQ9CsxAgMAAAGEzGe5CQAnjQAeMfbznhjzQxt4h30ZLgyw5AWAUZYcWZFR9b8msilwjQ" -i  "https://a1-v2.easemob.com/1148220627103272/migo/users/842be6aaef302dbffb2edabca32ba11f" -d '{"notification_no_disturbing": false,"notification_no_disturbing_start": "0","notification_no_disturbing_end": "24"}'
        查
        curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer YWMtpy1QknFCEe2TujGacnLHDjagngqIQTVUsexhz-g5I-6VJ6Ny6VFEraDajvpQ9CsxAgMAAAGEzGe5CQAnjQAeMfbznhjzQxt4h30ZLgyw5AWAUZYcWZFR9b8msilwjQ' 'https://a1-v2.easemob.com/1148220627103272/migo/users/8cfd70525f750dff90c9d3abb5dcb487'

        新版
        notification_no_disturbing：false
        https://docs-im.easemob.com/ccim/rest/pushconfig?s[]=免打扰#设置离线推送设置

     * @param member_uuid
     * @param im_on_off 1 开
     * @throws \Exception
     */
    public static function offlinePush(string $member_uuid = '', int $im_on_off = 1)
    {
        $auth = EasemobUserAuth::auth();
        $easemobToken = $auth->getEasemobToken();
        $apiUr = $auth->getBaseUri();
        $headers = $auth->headers();

        $username = UtilService::memberUuidToImAccount($member_uuid);

        // $uri = $apiUr.'/users/'.$username.'/notification/user/'.$username;
        // $data['type'] = 'NONE';
        // $data['ignoreInterval'] = '00:00-23:59';
        // $data['ignoreDuration'] = 604800000 ;

        $uri = $apiUr.'/users/'.$username;
        $data = '{"notification_no_disturbing": '.$im_on_off.',"notification_no_disturbing_start": "0","notification_no_disturbing_end": "24"}';

        $resp = Http::put($uri, $data, $headers);
        if (!$resp->ok()) {
            Log::alert(var_export($resp,true));
        }
        return true;
    }
    
}